package com.chenxin.interact.handler.rcsHandler;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chenxin.common.constant.WcsConstants;
import com.chenxin.common.utils.StringUtils;
import com.chenxin.interact.domain.UrlMap;
import com.chenxin.interact.domain.dto.AgvTaskDTO;
import com.chenxin.interact.domain.dto.RcsResultHkDTO;
import com.chenxin.wms.domain.AgvTaskEntity;
import com.chenxin.wms.mapper.AgvTaskMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Component("PostTaskRequest")
@Slf4j
public class PostTaskRequest {
    @Autowired
    private AgvTaskMapper agvTaskMapper;

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public void call(UrlMap urlMap) {
        // 检索是否存在待下发的任务
        QueryWrapper<AgvTaskEntity> taskQW = new QueryWrapper<>();
        taskQW.lambda().eq(AgvTaskEntity::getAgvStatus, 0)
                .orderByAsc(AgvTaskEntity::getCreateDate).last("limit 1");
        AgvTaskEntity agvTask = agvTaskMapper.selectOne(taskQW);
        if (agvTask == null) {
            log.info("[RCS]无待下发的任务!");
            return;
        }
        if (StringUtils.isNull(agvTask.getPositionCodePath())) {
            log.info("待下发任务ID【" + agvTask.getAgvId() + "】路线信息不能为空!");
            return;
        }
        // 解析搬送路径
        List<String> pathMap = Arrays.asList(agvTask.getPositionCodePath().split("#"));
        List<AgvTaskDTO.PositionPathDTO> positionPaths = pathMap.stream().map(path -> {
            AgvTaskDTO.PositionPathDTO positionPathDTO = new AgvTaskDTO.PositionPathDTO();
            positionPathDTO.setPositionCode(path);
            positionPathDTO.setType("1");
            return positionPathDTO;
        }).collect(Collectors.toList());
        // 将待下发任务封装成RCS请求
        AgvTaskDTO taskDTO = new AgvTaskDTO();
        taskDTO.setReqCode(agvTask.getReqCode());
        taskDTO.setTaskCode(agvTask.getTaskCode());
        taskDTO.setTaskTyp(agvTask.getTaskTyp());
        taskDTO.setCtnrCode(agvTask.getCtnrCode());
        taskDTO.setCtnrTyp(agvTask.getCtnrTyp());
        taskDTO.setPositionCodePath(positionPaths);
        // 通过接口将封装的任务下发至RCS系统
        WebClient client = WebClient.builder()
                .baseUrl(urlMap.getUriAdr())
                .build();

        RcsResultHkDTO response = client.post()
                .uri(urlMap.getUrlAdr())
                .bodyValue(taskDTO)
                .retrieve()
                .bodyToMono(RcsResultHkDTO.class)
                .block();
        assert response != null;
        // 收到反馈后根据反馈码做处理
        if (WcsConstants.PROC_CODE_SUCCESS.equals(response.getCode())) {
            agvTask.setAgvStatus(WcsConstants.HK_STATUS_POST);
            agvTask.setData("指令成功下发");
        } else {
            agvTask.setAgvStatus(WcsConstants.HK_STATUS_ERROR);
            agvTask.setData("指令下发失败，RCS反馈：" + response.getMessage());
        }
        // 更新任务信息
        agvTask.setReqTime(dateFormat.format(new Date()));
        agvTask.setUpdateDate(new Date());
        agvTaskMapper.updateById(agvTask);
    }
}
